<template>
  <el-image
    :src="`${realSrc}`"
    fit="cover"
    :style="`width:${realWidth};height:${realHeight};`"
    :preview-src-list="realSrcList"
  >
    <div slot="error" class="image-slot">
      <i class="el-icon-picture-outline"></i>
    </div>
  </el-image>
</template>

<script>
import { isExternal } from "@/utils/validate";

export default {
  name: "ImagePreview",
  props: {
    src: {
      type: [String, Array, Object],
      default: ""
    },
    width: {
      type: [Number, String],
      default: ""
    },
    height: {
      type: [Number, String],
      default: ""
    }
  },
  computed: {
    normalizedSources() {
      const sources = [];
      const push = (value) => {
        if (value === undefined || value === null) return;
        const str = String(value).trim();
        if (str) {
          sources.push(str);
        }
      };

      const raw = this.src;
      if (Array.isArray(raw)) {
        raw.forEach(push);
      } else if (typeof raw === "string") {
        const trimmed = raw.trim();
        if (!trimmed) {
          return sources;
        }
        if (/^\[.*\]$/.test(trimmed)) {
          try {
            const parsed = JSON.parse(trimmed);
            if (Array.isArray(parsed)) {
              parsed.forEach(push);
            } else if (parsed) {
              push(parsed.url || parsed.path || parsed);
            }
          } catch (error) {
            trimmed.split(",").forEach(push);
          }
        } else {
          trimmed.split(",").forEach(push);
        }
      } else if (typeof raw === "object" && raw !== null) {
        push(raw.url || raw.path || raw.src || raw);
      }

      return sources;
    },
    realSrc() {
      const first = this.normalizedSources[0];
      return this.resolvePath(first);
    },
    realSrcList() {
      return this.normalizedSources.map((item) => this.resolvePath(item));
    },
    realWidth() {
      return typeof this.width == "string" ? this.width : `${this.width}px`;
    },
    realHeight() {
      return typeof this.height == "string" ? this.height : `${this.height}px`;
    }
  },
  methods: {
    resolvePath(path) {
      if (!path) return "";
      const url = ("" + path).trim();
      if (isExternal(url)) {
        return url;
      }
      const join = (prefix, sub) => {
        if (!prefix) return sub;
        const safePrefix = prefix.replace(/\/$/, "");
        const needsSlash = !sub.startsWith("/") && !safePrefix.endsWith("/");
        return `${safePrefix}${needsSlash ? "/" : ""}${sub}`;
      };
      const apiBase = process.env.VUE_APP_BASE_API || "";
      let fileBase = process.env.VUE_APP_FILE_BASE_URL || "";
      if (!fileBase) {
        if (/^https?:\/\//i.test(apiBase)) {
          fileBase = apiBase;
        } else if (apiBase) {
          fileBase = apiBase;
        } else if (typeof window !== 'undefined') {
          fileBase = window.location.origin || '';
        }
      }
      const resourcePrefixes = ["/profile/", "profile/", "/upload/", "upload/", "/common/download", "common/download"];
      const isResource = resourcePrefixes.some(prefix => url.startsWith(prefix));
      if (isResource) {
        const normalized = url.startsWith("/") ? url : `/${url}`;
        return join(fileBase || apiBase, normalized);
      }
      if (!apiBase) {
        return url.startsWith("/") ? url : `/${url}`;
      }
      const normalized = url.startsWith("/") ? url : `/${url}`;
      return join(apiBase, normalized);
    }
  },
};
</script>

<style lang="scss" scoped>
.el-image {
  border-radius: 12px;
  background-color: rgba(241, 245, 249, 0.8);
  box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
  ::v-deep .el-image__inner {
    transition: all 0.3s;
    cursor: pointer;
    &:hover {
      transform: scale(1.06);
    }
  }
  ::v-deep .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    color: #909399;
    font-size: 30px;
  }
}
</style>
